import os
import time
import logging

def set_fan_speed(speed):
    os.system(f"C:\\Users\c206\Desktop\温控脚本\IPMICFG-Win.exe -raw 0x30 0x70 0x66 0x01 0x00 0x{speed}")
    os.system(f"C:\\Users\c206\Desktop\温控脚本\IPMICFG-Win.exe -raw 0x30 0x70 0x66 0x01 0x01 0x{speed}")
    os.system(f"C:\\Users\c206\Desktop\温控脚本\IPMICFG-Win.exe -raw 0x30 0x70 0x66 0x01 0x02 0x{speed}")
    os.system(f"C:\\Users\c206\Desktop\温控脚本\IPMICFG-Win.exe -raw 0x30 0x70 0x66 0x01 0x03 0x{speed}")

def get_cpu_status():
    cmd_output = os.popen("C:\\Users\c206\Desktop\温控脚本\IPMICFG-Win.exe -sdr")
    cpu_status = cmd_output.read().split('\n')[2:4]
    cpu1 =  int(cpu_status[0].split("|")[2].replace(" ","")[:2])
    cpu2 = int(cpu_status[1].split("|")[2].replace(" ", "")[:2])
    return cpu1,cpu2

def get_gpu_status(gpu_count):
    # pynvml.nvmlInit()
    # gpu_count = pynvml.nvmlDeviceGetCount()
    # gpu_list = []
    # for device_index in range (gpu_count):
    #     handle = pynvml.nvmlDeviceGetHandlebyIndex(devide_index)
    #     gpu_status = pynvml.nvmlDevideGetTemperature(handle,0)
    #     gpu_list += gpu_status
    gpu_list = []
    cmd_output = os.popen("NVIDIA-SMI")
    cmd_output = cmd_output.read().split("\n")
    for device_index in range(gpu_count):
        line = cmd_output[8+3*device_index]
        gpu_temp = int(line.split("%")[1].split("C")[0])
        gpu_list.append(gpu_temp)
    return gpu_list


# 初始化日志
logger = logging.getLogger('temprature')
logger.setLevel(logging.INFO)
log_file = logging.FileHandler('C:\\Users\c206\Desktop\\temprature.log')
log_file.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(message)s')
log_file.setFormatter(formatter)
logger.addHandler(log_file)

# 设置初始速度为10
fanspeed = 10
set_fan_speed(fanspeed)
while(True):
    # 获取cpu 和 gpu 温度
    cpu1,cpu2  = get_cpu_status()
    gpu0,gpu1,gpu2,gpu3 = get_gpu_status(4)
    if cpu1 > 65 or cpu2 > 65 or gpu0 > 75 or gpu1 > 75 or gpu2 > 75 or gpu3 > 75:
        fanspeed_temp = 15
    elif cpu1>70 or cpu2>70 or gpu0>80 or gpu1>80 or gpu2>80 or gpu3>80:
        fanspeed_temp = 20
    elif cpu1>75 or cpu2>75 or gpu0>85 or gpu1>85 or gpu2>85 or gpu3>85:
        fanspeed_temp = 30
    elif cpu1 > 80 or cpu2 > 80 or gpu0 > 90 or gpu1 > 90 or gpu2 > 90 or gpu3 > 90:
        fanspeed_temp = 40
    else:
        fanspeed_temp = 10
    if fanspeed != fanspeed_temp:
        fanspeed = fanspeed_temp
        set_fan_speed(fanspeed)
    logger.info (f"cpus: {cpu1} {cpu2} gpus: {gpu0} {gpu1} {gpu2} {gpu3} fanspeed : {fanspeed}")
    time.sleep(5)
